package ru.tennisworld.user.service.users.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ru.tennisworld.user.entities.TennisUserProfile;
import ru.tennisworld.user.exceptions.TennisUserServiceException;
import ru.tennisworld.user.mappers.TennisUserProfileMapper;
import ru.tennisworld.user.repositories.TennisUserProfileRepository;
import ru.tennisworld.user.service.ValidationService;
import ru.tennisworld.user.service.users.TennisUserProfileService;

@Service("tennisUserProfileService")
public class TennisUserProfileServiceImpl implements TennisUserProfileService {

    @Autowired
    private ValidationService validationService;

    @Autowired
    private TennisUserProfileRepository profileRepository;

    @Autowired
    private TennisUserProfileMapper profileMapper;

    private static final Logger LOG = LoggerFactory.getLogger(TennisUserProfileServiceImpl.class);

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public TennisUserProfile createBaseProfile() {
        TennisUserProfile result = new TennisUserProfile();
        result.setRating(1000L);
        profileRepository.save(result);
        return result;
    }

    @Override
    public TennisUserProfile getTennisUserProfile(Long id) {
        LOG.info("operation=TennisUserProfileServiceImpl.getTennisUserProfile, action=start, userId={}", id);
        TennisUserProfile result = profileRepository.findById(id).orElseThrow(
                () -> new TennisUserServiceException("Профиль пользователя не найден"));
        LOG.info("operation=TennisUserProfileServiceImpl.getTennisUserProfile, action=end, profile={}", result);
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public TennisUserProfile updateTennisUserProfile(TennisUserProfile upd, TennisUserProfile src) {
        LOG.info("operation=TennisUserProfileServiceImpl.updateTennisUserProfile, action=start, updProfile={}", upd);
        profileMapper.updateUserProfile(src, upd);
        validationService.validateTennisUserProfileInfo(upd);
        profileRepository.save(upd);
        LOG.info("operation=TennisUserProfileServiceImpl.updateTennisUserProfile, action=end, updProfile={}", upd);
        return upd;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void deleteTennisUserProfile(Long id) {
        LOG.info("operation=TennisUserProfileServiceImpl.deleteTennisUserProfile, action=start, userId={}", id);
        TennisUserProfile deleteProfile = getTennisUserProfile(id);
        profileRepository.delete(deleteProfile);
        LOG.info("operation=TennisUserProfileServiceImpl.deleteTennisUserProfile, action=end");
    }
}
